package com.webxiaohua.algorithm.linkedlist;

import java.util.HashSet;

/***
 * 判断链表是否有环
 */
public class FindCycle {

    /**
     * @desc 生成链表
     * @param node
     * @return
     */
    public static Node generateNode(Node node){
        if(node.id<5){
            node.next = new Node(node.id + 1);
            generateNode(node.next);
        }else{
            node.next = node;
        }
        return node;
    }

    public static void main(String... args){
        Node node = new Node(0);
        node = generateNode(node);
        HashSet<Node> set = new HashSet<>();
        boolean existCycle = false;
        while(node.next!=null){
            if(set.contains(node)){
                existCycle = true;
                break;
            }else{
                set.add(node);
                node = node.next;
            }
        }
        if(existCycle){
            System.out.println("存在环引用");
        }else{
            System.out.println("不存在环引用");
        }
    }
}
